<template>
  <div class="direction-selection-page">
    <!-- 顶部标题栏 -->
    <div class="header">
      <div class="logo-container">
        <h1 class="system-title">专业方向选择系统</h1>
      </div>
      <div class="header-actions">
        <el-button type="primary" size="small" @click="showSetDeadline" v-if="hasAuth('sys_major:put')">设置截止时间</el-button>
        <div class="deadline-info">
          <span class="deadline-label">截止时间: {{ deadline }}</span>
        </div>
      </div>
    </div>

    <div class="main-content">
      <!-- 内容区 -->
      <div class="content">
        <div class="section student-info">
          <h2 class="section-title">学生信息</h2>
          <div class="info-grid">
            <div class="info-item">
              <span class="info-label">姓名：</span>
              <span class="info-value">{{ studentInfo.name }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">学号：</span>
              <span class="info-value">{{ studentInfo.studentId }}</span>
            </div>
            <div class="info-item">
              <span class="info-label">班级：</span>
              <span class="info-value">{{ studentInfo.class }}</span>
            </div>
          </div>
        </div>

        <div class="section grades-info">
          <div class="grades-header">
            <h2 class="section-title">成绩信息</h2>
            <div class="average-score">平均分: {{ averageScore }}</div>
          </div>
          <div class="grades-table">
            <table>
              <thead>
                <tr>
                  <th>课程</th>
                  <th>成绩</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(grade, index) in studentInfo.grades" :key="index">
                  <td>{{ grade.subject }}</td>
                  <td>
                    <span class="score" :class="getScoreClass(grade.score)">{{ grade.score }}</span>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>

        <div class="section direction-selection">
          <h2 class="section-title">专业方向志愿填报</h2>

          <div class="selection-notice">
            请选择您的专业方向志愿，可填报两个志愿。在截止时间前，您可以随时修改您的选择。
          </div>

          <div class="selection-form">
            <div class="form-group">
              <label class="form-label">第一志愿</label>
              <el-select v-model="form.firstChoice" placeholder="请选择专业方向" filterable class="direction-select"
                :disabled="isSubmitting || isDeadlinePassed">
                <el-option v-for="item in directionOptions" :key="item.value" :label="item.label" :value="item.label"
                  :disabled="form.secondChoice === item.label"></el-option>
              </el-select>
            </div>

            <div class="form-group">
              <label class="form-label">第二志愿</label>
              <el-select v-model="form.secondChoice" placeholder="请选择专业方向" filterable class="direction-select"
                :disabled="isSubmitting || isDeadlinePassed">
                <el-option v-for="item in directionOptions" :key="item.value" :label="item.label" :value="item.label"
                  :disabled="form.firstChoice === item.label"></el-option>
              </el-select>
            </div>
          </div>

          <div class="selection-preview" v-if="form.firstChoice || form.secondChoice">
            <h3 class="preview-title">您的选择</h3>
            <div class="preview-content">
              <div class="preview-item" v-if="form.firstChoice">
                <span class="preview-label">第一志愿：</span>
                <el-tag size="medium" effect="plain">{{ getDirectionLabel(form.firstChoice) }}</el-tag>
              </div>
              <div class="preview-item" v-if="form.secondChoice">
                <span class="preview-label">第二志愿：</span>
                <el-tag size="medium" type="success" effect="plain">{{ getDirectionLabel(form.secondChoice) }}</el-tag>
              </div>
            </div>
          </div>

          <div class="form-actions">
            <el-button type="primary" :icon="hasVolunteerData ? 'el-icon-edit' : 'el-icon-check'"
               :disabled="!isFormValid || isDeadlinePassed || isSubmitting" @click="submitForm">
              {{ hasVolunteerData ? '修改志愿' : '提交志愿' }}
            </el-button>

            <el-button v-if="hasVolunteerData" icon="el-icon-refresh-left" @click="resetForm" :disabled="isSubmitting">
              重新选择
            </el-button>
          </div>

          <div class="deadline-warning" v-if="isDeadlinePassed">
            截止时间已过，无法修改志愿
          </div>
        </div>
      </div>
    </div>

    <!-- 添加时间设置弹窗 -->
    <el-dialog title="设置截止时间" :visible.sync="deadlineDialogVisible" width="400px">
      <el-date-picker v-model="deadlineTemp" type="datetime" placeholder="选择截止时间" align="center"
        :picker-options="pickerOptions" value-format="timestamp">
      </el-date-picker>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deadlineDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveDeadline">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'DirectionSelection',
  data() {
    return {
      hasVolunteerData: false, // 添加这个状态来控制按钮显示
      studentInfo: {
        name: '',
        studentId: '',
        class: '',
        grades: [
          { subject: '面向对象程序设计(java)', score: 0 },
          { subject: '程序设计基础', score: 0 },
          { subject: '网页设计与制作', score: 0 },
          { subject: '数据库应用技术', score: 0 }
        ]
      },
      form: {
        firstChoice: '',
        secondChoice: ''
      },

      isSubmitting: false,
      deadline: '',
      directionOptions: [],
      currentTime: new Date(),
      deadlineDialogVisible: false,
      deadlineTemp: '',
      deadlineTimestamp: 0,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        }
      },
    }
  },
  computed: {
    averageScore() {
      if (!this.studentInfo || !this.studentInfo.grades) {
        return '0.0';
      }
      const validScores = this.studentInfo.grades.filter(grade => !isNaN(grade.score));
      if (validScores.length === 0) {
        return '0.0';
      }
      const sum = validScores.reduce((total, grade) => total + Number(grade.score), 0);
      return (sum / validScores.length).toFixed(1);
    },
    isFormValid() {
      return this.form.firstChoice &&
        this.form.secondChoice &&
        this.form.firstChoice !== this.form.secondChoice;
    },
    isDeadlinePassed() {
      if (!this.deadlineTimestamp) return false;
      return Date.now() > Number(this.deadlineTimestamp);
    }
  },
  mounted() {
    this.getlist();
    this.getuserinfo();
  },
  methods: {
    getuserinfo() {
      this.$get('/api/studentInfo/ByStudentId').then(response => {
        console.log(response.data)
        if (response.code === 200) {
          let { studentId, name, id, className, webScore, javaScore, programScore, databaseScore, applicationOne, applicationTwo,endTime } = response.data;
          this.studentInfo.studentId = studentId;
          this.studentInfo.name = name;
          this.studentInfo.id = id;
          this.studentInfo.class = className;
          this.studentInfo.grades[0].score = javaScore
          this.studentInfo.grades[1].score = programScore
          this.studentInfo.grades[2].score = webScore
          this.studentInfo.grades[3].score = databaseScore
          this.form.firstChoice = applicationOne
          this.form.secondChoice = applicationTwo
          this.deadline = endTime
          // 根据是否有志愿数据来设置状态
          this.hasVolunteerData = applicationOne && applicationTwo;
        } else {
          this.$message.error('获取用户信息失败！');
        }
      }).catch(error => {
        console.error('Error fetching user info:', error);
      });
    },
    getlist() {
      this.$get('/api/majorDetails').then(response => {
        if (response.code === 200) {
          this.directionOptions = response.data.map(item => ({
            value: item.majorCode,
            label: item.majorName
          }));
        } else {
          this.$message.error('获取专业方向列表失败！');
        }
      }).catch(error => {
        console.error('Error fetching direction options:', error);
      });
    },
    getDirectionLabel(value) {
      const option = this.directionOptions.find(opt => opt.label === value);
      return option ? option.label : '';
    },
    getScoreClass(score) {
      if (score >= 90) return 'score-excellent';
      if (score >= 80) return 'score-good';
      if (score >= 70) return 'score-average';
      return 'score-normal';
    },
    submitForm() {
      // 检查当前时间是否超过截止时间
      const currentTime = new Date().getTime();
      const deadlineTime = new Date(this.deadline).getTime();
      console.log(currentTime, deadlineTime);
      if (currentTime > deadlineTime) {
        this.$message.warning('填报时间已过，无法提交');
        this.isSubmitting = true; // 禁用按钮
        return;
      }

      if (!this.isFormValid) {
        this.$message.warning('请完整填写志愿信息');
        return;
      }
      this.isSubmitting = true;
      const params = {
        studentId: this.studentInfo.studentId,
        id: this.studentInfo.id,
        applicationOne: this.form.firstChoice,
        applicationTwo: this.form.secondChoice
      };
      this.$put('/api/studentInfo', params)
        .then(res => {
          if (res.code === 200) {
            if(this.hasVolunteerData){
              this.$message.success('志愿修改成功');
            }
            else{
              this.$message.success('志愿提交成功');
            }
            this.getuserinfo();
          } else {
            this.$message.error(res.msg || '提交失败');
          }
        })
        .catch(err => {
          console.error('提交志愿失败:', err);
          this.$message.error('提交失败');
        })
        .finally(() => {
          this.isSubmitting = false;
        });
    },
    resetForm() {
      if (this.isDeadlinePassed) {
        this.$message.warning('填报时间已过，无法重置');
        return;
      }
      this.form.firstChoice = '';
      this.form.secondChoice = '';
      this.hasVolunteerData = false;
    },
    showSetDeadline() {
      this.deadlineDialogVisible = true;
    },
    // 修改保存截止时间的方法
    saveDeadline() {
      if (this.deadlineTemp) {
        this.deadlineTimestamp = this.deadlineTemp;
        const formattedTime = this.formatDateTimeForBackend(new Date(Number(this.deadlineTemp)));
        this.endTime = formattedTime
        console.log(this.endTime);

        // 调用接口更新截止时间
        this.$put(`/api/studentInfo/updateEndTime?endTime=${this.endTime}`)
          .then(res => {
            if (res.code === 200) {
              this.deadline = this.formatDateTime(new Date(Number(this.deadlineTemp)));
              this.$message.success('截止时间设置成功');
              this.checkDeadline(); // 立即检查时间状态
            } else {
              this.$message.error(res.msg || '设置失败');
            }
          })
          .catch(err => {
            // console.error('设置截止时间失败:', err);
            // this.$message.error('设置失败');
          });
      }
      this.deadlineDialogVisible = false;
    },
    // 添加后端所需的时间格式化方法
    formatDateTimeForBackend(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hour = String(date.getHours()).padStart(2, '0');
      const minute = String(date.getMinutes()).padStart(2, '0');
      const second = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    },
    formatDateTime(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hour = String(date.getHours()).padStart(2, '0');
      const minute = String(date.getMinutes()).padStart(2, '0');
      const second = String(date.getSeconds()).padStart(2, '0');
      return `${year}年${month}月${day}日 ${hour}:${minute}:${second}`;
    }
  }
}
</script>

<style scoped>
.direction-selection-page {
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 顶部标题栏 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.logo-container {
  display: flex;
  align-items: center;
}

.logo {
  margin-right: 10px;
}

.system-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

.deadline-info {
  background-color: #f0f9eb;
  color: #67c23a;
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 14px;
}

/* 主内容区 */
.main-content {
  padding: 20px;
}

/* 内容区 */
.content {
  max-width: 1200px;
  margin: 0 auto;
}

.section {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  padding: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-top: 0;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

/* 学生信息 */
.info-grid {
  display: flex;
  flex-wrap: wrap;
}

.info-item {
  margin-right: 40px;
  margin-bottom: 10px;
}

.info-label {
  color: #606266;
}

.info-value {
  color: #303133;
  font-weight: 500;
  margin-left: 5px;
}

/* 成绩信息 */
.grades-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.average-score {
  font-size: 15px;
  color: #409eff;
  font-weight: 500;
}

.grades-table {
  width: 100%;
  overflow-x: auto;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 500;
  text-align: left;
  padding: 12px 15px;
}

td {
  padding: 12px 15px;
  border-bottom: 1px solid #ebeef5;
}

.score {
  display: inline-block;
  padding: 2px 8px;
  border-radius: 3px;
  font-weight: 500;
}

.score-excellent {
  background-color: #f0f9eb;
  color: #67c23a;
}

.score-good {
  background-color: #ecf5ff;
  color: #409eff;
}

.score-average {
  background-color: #fdf6ec;
  color: #e6a23c;
}

.score-normal {
  background-color: #f4f4f5;
  color: #606266;
}

/* 专业方向选择 */
.selection-notice {
  background-color: #f4f4f5;
  color: #606266;
  padding: 10px 15px;
  border-radius: 4px;
  margin-bottom: 20px;
  font-size: 14px;
}

.selection-form {
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #606266;
}

.direction-select {
  width: 100%;
}

.selection-preview {
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 15px;
  margin-bottom: 20px;
}

.preview-title {
  font-size: 15px;
  font-weight: 500;
  color: #606266;
  margin-top: 0;
  margin-bottom: 15px;
}

.preview-content {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.preview-item {
  display: flex;
  align-items: center;
}

.preview-label {
  width: 80px;
  color: #606266;
}

.form-actions {
  display: flex;
  gap: 15px;
  margin-top: 20px;
}

.deadline-warning {
  color: #f56c6c;
  background-color: #fef0f0;
  padding: 10px 15px;
  border-radius: 4px;
  margin-top: 20px;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .info-grid {
    flex-direction: column;
  }

  .form-actions {
    flex-direction: column;
  }

  .form-actions .el-button {
    width: 100%;
  }
}
</style>